;
cmedit.CmsTargetTest = (function($, window, document) {
	var userId = '';
	var token = '';
	var userName = '';
	var tenantId = '';
	var thisContext;
	var currentpage = 1; // 当前页，全局变量，用于分页功能的实现
	var allrowNumber = 10; // 总共的列表行数
	var pageSize = 10;
	var isupdateOrAdd = 0; // cre签发修改或者添加
	var oldSelectedObj = null; // 用于选中列表样式改变，同时去除已选择样式。该值保持原有选中行的对象，默认为null
	var isSingleSelect = 0;// 是否可以选择栏目 0可以1不可以
	var isDeleteChecked = 0;// 是否可以删除栏目 0可以1不可以
	var columnlist = [];// 已存数据数据的栏目
	var myobj = [];// 所有栏目
	var allColumnIds = new Array();
	var myColumnIds = new Array();
	var cmsTargetType;//cms分发类型(后台配置)：1:MXU;2:M2O;3:M2Oplus4:融合号
	//var myColumnNames = new Array();
	var CmsTargetTestClass = function(){
		
	};
	
	CmsTargetTestClass.prototype = {
			
		init : function(){
			thisContext = this;
			thisContext.initUserSession();
			thisContext.initData();
			thisContext.initEvent();
		},
		/**
		 * 初始化用户信息
		 * @returns {Boolean}
		 */
		initUserSession: function () {
        	token = cmedit.global.getParameterFromUrl("token");
        	userId = cmedit.global.getParameterFromUrl("userId");
        	userName = cmedit.global.getParameterFromUrl("userName");
        	tenantId = cmedit.global.getParameterFromUrl("tenantId");
        	cmsTargetType = cmedit.global.getParamterByCode(cmedit.global.cmsTargetTypeCode,cmedit.global.cmedit_server_code);
        	if(!cmedit.global.isNotEmpty(token)){
        		alert("token为空");
        		return false;
        	}
        	if(!cmedit.global.isNotEmpty(userId)){
        		alert("userId为空");
        		return false;
        	}
        	if(!cmedit.global.isNotEmpty(userName)){
        		alert("userName为空");
        		return false;
        	}
        	if(!cmedit.global.isNotEmpty(tenantId)){
        		alert("tenantId为空");
        		return false;
        	}
        },
        
        initData : function(){
        	thisContext.initColumn();
        	thisContext.listCreTarget(1);
        	var allColumnList = $(".tube_check");
        },
        
        /**
         * 初始化栏目
         */
        initColumn : function(){
        	var columnName = $("#columnName").val();
        	var postData = {
        		columnName : columnName,
            	key : window.localStorage.getItem("portalKey")
            };
        	allColumnIds.splice(0,allColumnIds.length);
        	thisContext.ajaxRequest({
				type: "post",
				async: false,
				dataType: "json",
				url: cmedit.global.cmsPath+"UserInfoController/fuzzySearchColumn",
				data : postData,
				success: function(data) {
					if(data.status) {
						myobj = data.data;
						var columns = data.data;
						for(var i = 0;i < columns.length;i++){
							allColumnIds.push(columns[i].id);
						}
						var data = {
							list : columns
						}
						var columnhtml = template('columnList_html', data);
						$('#columnList').html(columnhtml);
						// 将以选中的栏目回显到待选列表
						thisContext.getSelectedColumn();
						if (myobj.length > 0) {
							for (var i = 0; i < myobj.length; i++) {
								if (columnlist.length > 0) {
									for (var j = 0; j < columnlist.length; j++) {
										if (myobj[i].id == columnlist[j].columnId) {
											$("#" + myobj[i].id).removeClass(
													"icon-radio");
											$("#" + myobj[i].id).addClass(
													"icon-radio-checked");
										}
									}
								}
							}
						}
						thisContext.checkedNum();
						$(".one").removeClass("tube_check_disabled").addClass("tube_check");
						$(".all").removeClass("tube_check_disabled").addClass("tube_check");
						//$(".one").removeClass("tube_check").addClass("tube_check_disabled");
						//$(".all").removeClass("tube_check").addClass("tube_check_disabled");
					}else{
						alert("初始化栏目失败");
					}
				}
			});
        },
        
        /**
         * 获取选中的栏目信息
         */
        getSelectedColumn : function(){
        	columnlist = [];
        	var columnsObj = $(".tube_close");
        	if (columnsObj.length > 0) {
        		for (var i = 0; i < columnsObj.length; i++) {
        			var columnObj = {};
        			var columns = columnsObj[i].id
        					.substring(3, columnsObj[i].id.length);
        			var column = columns.split("&&");
        			columnObj.columnId = column[0];
        			columnObj.columnName = column[1];
        			columnlist.push(columnObj);
        		}
        	} else{
        		columnlist = [];
        	}
        },
        
        changeColumnList : function(){
        	var allColumnList = $(".tube_check");
        	for(var i = 0;i < myColumnIds.length;i++){
        		for(var j =0;j < allColumnList.length;j++){
        			var nowColumn = $(allColumnList[j]);
        			if(myColumnIds[i] == nowColumn.attr("id")){
        				nowColumn.removeClass('icon-radio');
        				nowColumn.addClass('icon-radio-checked');
        				break;
        			}
        		}
        	}
        },
        
        
        
        /**
         * 初始化事件
         */
        initEvent : function(){
        	$("#saveCreTarget").off("click");
        	$("#addCreTarget").off("click");
        	$("#updateCreTarget").off("click");
        	$("#deleteCreTarget").off("click");
        	$("#searchCreTarget").off("click");
        	$("#searchColumn").off("click");
        	$("#cancelCreTarget").off("click");
        	
        	$("#addCreTarget").on('click', function() {
        		thisContext.addCreTarget();
        	});
        	
        	$("#saveCreTarget").on('click', function() {
        		thisContext.createOrUpdateCreTarget();
        	});
        	
        	$("#updateCreTarget").on('click', function() {
        		if($("#cmsTargetGuid").val()){
        			thisContext.enablerightDiv("rightDiv");
        		}else{
        			alert("请选择一条修改数据");
        		}
        	});
        	
        	$("#cancelCreTarget").on('click', function() {
        		thisContext.listCreTarget(1);
        	});
        	
        	$("#searchCreTarget").on('click', function() {
        		thisContext.listCreTarget(1);
        	});
        	
        	$("#deleteCreTarget").on('click', function() {
        		if($("#cmsTargetGuid").val()){
        			thisContext.deleteCreTarget();
        		}else{
        			alert("请选择一条删除数据");
        		}
        	});
        	
        	$("#searchColumn").on('click', function() {
				thisContext.initColumn();
				//thisContext.changeColumnList();
			});
        	
        	$(".all").off('click').on('click',function(){
        		thisContext.enableAllIcon();
        	})
        	
        	//搜索框回车事件
			$('#searchTargetName').on('keypress',function(){
				if(event.keyCode==13){  
					thisContext.listCreTargetByCondition(1); 
				   }   
			});
        },
        
        /**
         * 展现签发列表
         * @param curpage
         */
        listCreTarget : function(curpage){
        	var searchTargetName = $("#searchTargetName").val();
        	thisContext.getCreTargetListByPage(curpage, searchTargetName);
        	thisContext.disablerightDiv("rightDiv");
        	$('#creTargetTable tr:eq(0)').click();
        	/*var firstCensorStrategyId = "";
        	var selectedObject = null;
        	selectedObject = $("#creTargetList tr:eq(0)");
        	$("#creTargetList tr:eq(0)").find("input").each(function(index, item) {
        		firstCensorStrategyId = $(item).attr("id");
        	});
        	downloadPathDetail(firstCensorStrategyId, selectedObject);*/
        },
        
        
        /**
         * 从后端获取签发列表
         * @param curpage
         * @param searchTargetName
         */
        getCreTargetListByPage : function(curpage,searchTargetName){
        	var postData = {
				"currentPage":curpage,
				"pageSize" : pageSize,
				"cmsTargetName" : searchTargetName,
				"creTargetType" : 0
			};
        	
        	thisContext.ajaxRequest({
				async : false,
				url : cmedit.global.cmsPath
				+ "CmsTargetController/getCmsTargetByPage",
				type : 'POST',
				data : postData,
				success : function(data){
					if (data.status == true || data.status == 'true') {
						thisContext.showData(data);
						thisContext.showPages(data);
					} else {
						alert(data.msg);
					}
				}
			});
        },
        
        /**
         * 单选框点击事件
         * @param id
         * @param name
         */
        enableSingleIcon : function(id, name){
        	if (isSingleSelect == 0) {
        		if ($("#" + id).hasClass('icon-radio-checked')) { // 如果已选中,取消勾选权限
        			$("#" + id).removeClass('icon-radio-checked');
        			$("#" + id).addClass('icon-radio');
        		} else {
        			$("#" + id).addClass('icon-radio-checked');
        			$("#" + id).removeClass('icon-radio');
        		}
        		var html = "";
        		if ($("#" + id).hasClass('icon-radio-checked')) {
        			html += '<tr id="checked'
        					+ id
        					+ '"><td width="90%">'
        					+ name
        					+ '</td><td><i id = "del'
        					+ id
        					+ '&&'
        					+ name
        					+ '"  onclick="javascript:deleteCheckedColumn(\''
        					+ id
        					+ '\',\''
        					+ name
        					+ '\')" class="icon iconfont icon-close tube_close"></i></td></tr>';
        		} else {
        			$("#checked" + id).remove();
        		}
        		$("#columns_checked").append(html);
        		thisContext.checkedNum();
        	}
        },
        
        /**
         * 计算所选栏目数量
         */
        checkedNum : function(){
        	var checkedColumnNum = $(".tube_close").length;
        	var columnsObj = $(".tube_close");
        	$("#columnNum").html(checkedColumnNum);
        	var size = 0;
        	if (allColumnIds.length > 0) {
        		for (var i = 0; i < allColumnIds.length; i++) {
        			if (columnsObj.length > 0) {
        				for (var j = 0; j < columnsObj.length; j++) {
        					var columns = columnsObj[j].id.substring(3,
        							columnsObj[j].id.length);
        					var column = columns.split("&&");
        					if (allColumnIds[i] == column[0]) {
        						size += 1;
        					}
        				}
        			}
        		}
        	}
        	if (size < allColumnIds.length) {
        		$('.all').removeClass('icon-radio-checked');
        		$('.all').addClass('icon-radio');
        	} else {
        		$('.all').addClass('icon-radio-checked');
        		$('.all').removeClass('icon-radio');
        	}
        },
        
        /**
         * 展示列表
         * @param data
         */
        showData : function(data){
        	var list = data.data.list;
			var data = {
				list : list
			};
			var creTargethtml = template('creTargetList_html', data);
			if (list.length == 0) {
				thisContext.clearCreTargetInput();
			}
			$('#creTargetTable').html(creTargethtml);
        },
        
        /**
         * 展示页码
         * @param data
         */
        showPages : function(data){
        	var pages = data.data;
			var data = {
				pages : pages
			}
			var pagehtml = template('parameter_page', data);
			$('#paging').html(pagehtml);
        },
        
        /**
         * 展示详情
         */
        showDetails : function(tr){
        	$(tr).parent().find("tr.trActive").toggleClass("trActive");//取消原先选中行
		    $(tr).toggleClass("trActive");//设定当前行为选中行
        	var trObj = $(tr);
        	var targetGuid = trObj.find('td').eq(0).text();
        	var columnId = trObj.find('td').eq(1).text();
        	var columnName = trObj.find('td').eq(2).text();
        	if(columnId.substr(columnId.length-1,1) == ","){
        		columnId=columnId.substring(1,columnId.length-1);
        	}
        	if(columnName.substr(columnName.length-1,1) == ","){
        		columnName=columnName.substring(0,columnName.length-1);
        	}
        	var columnIds = columnId.split(",");
        	var columnNames = columnName.split(",");
        	var cmsTargetHint = trObj.find('td').eq(3).text();
        	var cmsTargetAppid = trObj.find('td').eq(4).text();
        	var cmsTargetKey = trObj.find('td').eq(5).text();
        	var cmsTargetToken = trObj.find('td').eq(6).text();
        	var cmsTargetUrl = trObj.find('td').eq(7).text();
//        	var cmsTargetType = trObj.find('td').eq(8).text();
        	var cmsTargetName = trObj.find('td').eq(9).text();
//        	myColumnIds = columnIds;
        	//myColumnNames = columnNames;
        	//将栏目存入对象
        	for(var i = 0;i < columnIds.length;i++){
        		myColumnIds.push(columnIds[i]);
        	}
        	thisContext.clearCreTargetInput();
        	thisContext.initColumn();
        	$("#cmsTargetGuid").val(targetGuid);
        	$("#cmsTargetHint").val(cmsTargetHint);
        	$("#cmsTargetAppid").val(cmsTargetAppid);
        	$("#cmsTargetKey").val(cmsTargetKey);
        	$("#cmsTargetToken").val(cmsTargetToken);
        	$("#cmsTargetUrl").val(cmsTargetUrl);
        	$("#cmsTargetType").val(cmsTargetType);
        	$("#cmsTargetName").val(cmsTargetName);
        	//$("#creTargetType").val(creTargetType);
        	thisContext.writeColumnToList(columnIds,columnNames);
        	thisContext.disablerightDiv("rightDiv");
        },
        
        /**
         * 将存入的栏目反显
         * @param columnIds
         * @param columnNames
         */
        writeColumnToList : function(columnIds,columnNames){
        	var allColumnList = $(".tube_check");
        	var myColumnHtml = '<tr>' +
								'<td colspan="2"><span>已选择的栏目(<i id="columnNum"></i>)' +
								'</span></td>' +
								'</tr>';
        	var columnNumCount = 0;
        	for(var i = 0;i < columnIds.length;i++){
        		for(var j =0;j < allColumnList.length;j++){
        			var nowColumn = $(allColumnList[j]);
        			if(columnIds[i] == nowColumn.attr("id")){
        				columnNumCount ++;
        				nowColumn.removeClass('icon-radio');
        				nowColumn.addClass('icon-radio-checked');
        				myColumnHtml += '<tr id="checked'
        					+ columnIds[i]
        					+ '"><td width="90%">'
        					+ columnNames[i]
        					+ '</td><td><i id = "del'
        					+ columnIds[i]
        					+ '&&'
        					+ columnNames[i]
        					+ '"  onclick="cmedit.CmsTargetTest.deleteCheckedColumn(\''
        					+ columnIds[i]
        					+ '\',\''
        					+ columnNames[i]
        					+ '\')" class="icon iconfont icon-close tube_close"></i></td></tr>';
        				break;
        			}
        		}
        	}
        	$("#columns_checked").html(myColumnHtml);
        	$("#columnNum").html(columnNumCount);
        	thisContext.checkedNum();
        },
        
        /**
         * 新增签发
         */
        addCreTarget : function(){
        	thisContext.initEvent();
        	thisContext.enablerightDiv("rightDiv");
        	thisContext.clearCreTargetInput();
        },
        
        /**
         * 清空右侧表单
         */
        clearCreTargetInput : function(){
        	$("#cmsTargetGuid").val("");
        	$("#cmsTargetHint").val("");
        	$("#cmsTargetAppid").val("");
        	$("#cmsTargetKey").val("");
        	$("#cmsTargetToken").val("");
        	$("#cmsTargetUrl").val("");
        	//$("#cmsTargetType").val("");
        	$("#cmsTargetType option[value='"+ cmsTargetType +"']").attr("selected", true);
        	$("#cmsTargetName").val("");
        	$('.all').removeClass('icon-radio-checked');
        	$('.all').addClass('icon-radio');
        	$('.one').removeClass('icon-radio-checked');
        	$('.one').addClass('icon-radio');
        	for (var i = 0; i < allColumnIds.length; i++) {
        		$("#checked" + allColumnIds[i]).remove();
        	}
        	$("#columnNum").html("0");
        	$("#columnName").val("");
        },
        
        /**
         * 禁用右侧操作
         */
        disablerightDiv : function(divid){
        	$("#" + divid).find("input").each(function() {
        		$(this).attr("disabled", "disabled");
        	});
        	$("#" + divid).find("button").each(function() {
        		$(this).attr("disabled", "disabled");
        	});
        	$("#" + divid).find("textarea").each(function() {
        		$(this).attr("disabled", "disabled");
        	});
        	$("#" + divid).find("select").each(function() {
        		$(this).attr("disabled", "disabled");
        	});
        	
        	isSingleSelect = 1;// 是否可以选择栏目 0可以1不可以
        	isDeleteChecked = 1;
        },
        
        enablerightDiv : function(divid){
        	$("#" + divid).find("input").each(function() {
        		$(this).removeAttr("disabled");
        	});
        	$("#" + divid).find("button").each(function() {
        		$(this).removeAttr("disabled");
        	});
        	$("#" + divid).find("textarea").each(function() {
        		$(this).removeAttr("disabled");
        	});
//        	$("#" + divid).find("select").each(function() {
//        		$(this).removeAttr("disabled");
//        	});
        	isSingleSelect = 0;// 是否可以选择栏目 0可以1不可以
        	isDeleteChecked = 0;
        },
        
        
        
        //新增或者修改cre签发
		createOrUpdateCreTarget : function(){
			var columnsObj = $(".tube_close");
			var columnId = "";
			var columnName = "";
			if (columnsObj.length > 0) {
				for (var i = 0; i < columnsObj.length; i++) {
					var columns = columnsObj[i].id
							.substring(3, columnsObj[i].id.length);
					var column = columns.split("&&");
					columnId += column[0] + ",";
					columnName += column[1] + ",";
				}
			} else {
				alert("栏目不能为空！");// 栏目不能为空！
				return false;
			}
			var cmsTargetGuid = $("#cmsTargetGuid").val();
			var cmsTargetHint = $('#cmsTargetHint').val();
			var cmsTargetAppid = $('#cmsTargetAppid').val();
			var cmsTargetKey = $('#cmsTargetKey').val();
			var cmsTargetToken = $('#cmsTargetToken').val();
			var cmsTargetUrl = $('#cmsTargetUrl').val();
//			var cmsTargetType = $('#cmsTargetType').val();
			var cmsTargetName = $('#cmsTargetName').val();
			var postData = {
				"cmsTargetGuid":cmsTargetGuid,
				"cmsTargetHint":cmsTargetHint,
				"cmsTargetAppid":cmsTargetAppid,
				"columnId":columnId,
				"columnName" : columnName,
				"cmsTargetKey" : cmsTargetKey,
				"cmsTargetToken" : cmsTargetToken,
				"cmsTargetUrl" : cmsTargetUrl,
				"cmsTargetType" : cmsTargetType,
				"cmsTargetName" : cmsTargetName
			};
						
			thisContext.ajaxRequest({
				async : true,
				url : cmedit.global.cmsPath
				+ "CmsTargetController/updateCmsTarget",
				type : 'POST',
				data : postData,
				success : function(data){
					if (data.status == true || data.status == 'true') {
						$('.refe_deploy').show();
						$('.refe_new').hide();
						$('#sysPara').addClass('refe_on');
						$('#addPara').removeClass('refe_on').hide();
						alert("修改/新增成功");
						thisContext.disablerightDiv("rightDiv");
						thisContext.listCreTarget(1);
					} else {
						alert(data.msg);
					}
				}
			});
		},
		
		/**
		 * 
		 * @param id
		 * @param name
		 */
		deleteCheckedColumn : function(id, name) {
			if (isDeleteChecked == 0) {
				$("#" + id).removeClass('icon-radio-checked');
				$("#" + id).addClass('icon-radio');
				$("#checked" + id).remove();
				thisContext.checkedNum();
			}
		},
		
		/**
		 * 删除签发目标
		 */
		deleteCreTarget : function(){
			var cmsTargetGuid = $("#cmsTargetGuid").val();
			if(confirm("确定删除该签发目标?")){
				var cmsTargetGuids = new Array();
				cmsTargetGuids.push(cmsTargetGuid);
				var postData = {
						cmsTargetGuids : JSON.stringify(cmsTargetGuids)
				}
				
				thisContext.ajaxRequest({
					async : true,
					url : cmedit.global.cmsPath
					+ "CmsTargetController/deleteCmsTargetByGuids",
					type : 'POST',
					data : postData,
					success : function(data) {
						if (data.status == true || data.status == 'true') {
							alert("删除成功");
							thisContext.listCreTarget(1);
						} else {
							alert(data.msg);
						}
					}
				})
			}
		},
		
		/**
		 * 改变我的栏目对象
		 */
		deleteMyColumn : function(columnId){
			for (var i = 0; i < myColumnIds.length; i++) {
        		if(myColumnIds[i] == columnId){
        			
        		}
        	}
		},
		
		/**
		 * 全选栏目
		 */
		enableAllIcon : function(){
			if(isSingleSelect == 0){
				if ($('.all').hasClass('icon-radio-checked')) { // 如果已选中,取消勾选权限
					$('.all').removeClass('icon-radio-checked');
					$('.all').addClass('icon-radio');
					$('.one').each(function() {
						$(this).removeClass('icon-radio-checked');
						$(this).addClass('icon-radio');
					});
					if (myobj.length > 0) {
						for (var i = 0; i < myobj.length; i++) {
							$("#checked" + myobj[i].id).remove();
						}
						thisContext.checkedNum();
					}
				} else {
					$('.all').addClass('icon-radio-checked');
					$('.all').removeClass('icon-radio');
					$('.one').each(function() {
						$(this).addClass('icon-radio-checked');
						$(this).removeClass('icon-radio');
					});
					if (myobj.length > 0) {
						for (var i = 0; i < myobj.length; i++) {
							$("#checked" + myobj[i].id).remove();
						}
						var html = "";
						for (var i = 0; i < myobj.length; i++) {
							html += '<tr id="checked'
									+ myobj[i].id
									+ '"><td width="90%">'
									+ myobj[i].name
									+ '</td><td><i id = "del'
									+ myobj[i].id
									+ '&&'
									+ myobj[i].name
									+ '"  onclick="javascript:cmedit.ConfigDownloadPath.deleteCheckedColumn(\''
									+ myobj[i].id
									+ '\',\''
									+ myobj[i].name
									+ '\')" class="icon iconfont icon-close tube_close"></i></td></tr>';
						}
						$("#columns_checked").append(html);
						thisContext.checkedNum();
					}
				}
			}
		},
        
        /**
         * 封装的ajax请求
         * @param opts
         */
        ajaxRequest: function (opts) {
            // 一.设置默认参数
            var defaults = {
                url: '',
                type: '',
                data: '',
                cache: true,
                async: false,
                dataType: 'json',
//                contentType: "application/json;charset=UTF-8",
                success: function () {
                },
                error: function () {
                }
            };

            // 二.用户参数覆盖默认参数
            for (var key in opts) {
                defaults[key] = opts[key];
            }
            
            // 三.开始组装ajax
            $.ajax({
                url: defaults.url,
                type: defaults.type,
                data: defaults.data,
                async: defaults.async,
                cache: defaults.cache,
                dataType: defaults.dataType,
                contentType: defaults.contentType,
                beforeSend: function (XHR) {
                    XHR.setRequestHeader("userId", userId);
                    XHR.setRequestHeader("userName", encodeURIComponent(userName));
                    XHR.setRequestHeader("tenantId", tenantId);
                    XHR.setRequestHeader("token", token);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log("错误信息" + errorThrown.toString());
                },
                success: defaults.success
            });
        },
        
        
	};
	return new CmsTargetTestClass();
	
})(jQuery, window, document);
$(cmedit.CmsTargetTest.init());